﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using edowork.com.SQL2005;
using edowork.com.Model;

namespace WebInvoicingsys.system.checkstock
{
    public partial class checkstockset_edit : System.Web.UI.Page
    {
        public string alert_msg = "", Total_qty1 = "", Total_qty2="";

        //传入的参数
        string id, start_date, end_date, csid;

        /// <summary>
        /// 取得传入的参数
        /// </summary>
        /// <returns></returns>
        private bool GetParma()
        {
            try
            {
                id = Request.Params["id"].ToString();
                start_date = Request.Params["start_date"].ToString();
                end_date = Request.Params["end_date"].ToString();
                csid = Request.Params["csid"].ToString();
            }
            catch
            {
                //显示出错信息
                alert_msg = String.Format(Scripts.alert_warning, Errormsg.er_Parampost);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
                return false;
            }

            return true;
        }

        //绑定单据主信息
        private void BindInfo()
        {
            Execute exec = new Execute(Session["connectionString"].ToString());

            string sql = "", error_msg = "";

            //构造SQL语句
            sql = @"select a.csid,
                           a.billdate,
                           a.warehouseid,
                           (select warehouse.warehousename from warehouse where a.warehouseid=warehouse.warehouseid) warehousename,
                           a.remark
                      from check_stock a
                       where a.csid='{0}'";

            sql = String.Format(sql, id);

            DataSet ds = exec.ExecSQLQueryDataSet(sql, ref error_msg);

            if ((ds == null) || (ds.Tables.Count <= 0) || (ds.Tables[0].Rows.Count <= 0))
            {
                alert_msg = String.Format(Scripts.alert_warning, error_msg);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
                return;
            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                txt_csid.Text = dr["csid"].ToString();
                txt_billdate.Text = dr["billdate"].ToString();
                txt_warehousename.Text = dr["warehousename"].ToString();
                txt_remark.Text = dr["remark"].ToString();

                uc_from_area.setArea(dr["warehouseid"].ToString());
                uc_from_storageset.SetByWarehouse("");
            }
        }

        //绑定Session中的货品数据
        private void Bind()
        {
            DataTable dtList = new DataTable();

            dtList.Columns.Add("dgvID");
            dtList.Columns.Add("id");
            dtList.Columns.Add("areaname");
            dtList.Columns.Add("storagename");
            dtList.Columns.Add("productcode");
            dtList.Columns.Add("productname");
            dtList.Columns.Add("productshortname");
            dtList.Columns.Add("goodsclassname");
            dtList.Columns.Add("goodsunitname");
            dtList.Columns.Add("goodsspecname");
            dtList.Columns.Add("stackname");
            dtList.Columns.Add("guardname");
            dtList.Columns.Add("qty1");
            dtList.Columns.Add("qty2");

            DataTable dtData = ((checkstockset_product_class)Session["checkstockset_product"]).getList().Copy();

            foreach (DataRow dr in dtData.Rows)
            {
                DataRow drnew = dtList.NewRow();

                drnew["dgvID"] = (dtList.Rows.Count + 1).ToString();
                drnew["id"] = dr["id"].ToString();
                drnew["areaname"] = dr["areaname"].ToString();
                drnew["storagename"] = dr["storagename"].ToString();
                drnew["productcode"] = dr["productcode"].ToString();
                drnew["productname"] = dr["productname"].ToString();
                drnew["productshortname"] = dr["productshortname"].ToString();
                drnew["goodsclassname"] = dr["goodsclassname"].ToString();
                drnew["goodsunitname"] = dr["goodsunitname"].ToString();
                drnew["goodsspecname"] = dr["goodsspecname"].ToString();
                drnew["stackname"] = dr["stackname"].ToString();
                drnew["guardname"] = dr["guardname"].ToString();
                drnew["qty1"] = dr["qty1"].ToString();
                drnew["qty2"] = dr["qty2"].ToString();

                dtList.Rows.Add(drnew);
            }

            rplist.DataSource = dtList;
            rplist.DataBind();
        }

        //保存实盘数
        private void Save(string id, string qty2)
        {
            if (String.IsNullOrEmpty(id))
            {
                return;
            }

            if (String.IsNullOrEmpty(qty2))
            {
                return;
            }

            ((checkstockset_product_class)Session["checkstockset_product"]).UpdateQty2(id, qty2);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ;
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetParma();

                try
                {
                    ((checkstockset_product_class)Session["checkstockset_product"]).Reset();
                }
                catch
                {
                    Session.Add("checkstockset_product", new checkstockset_product_class(Session["connectionString"].ToString()));
                }
                finally
                {
                    ((checkstockset_product_class)Session["checkstockset_product"]).getDataList(id);
                }

                BindInfo();

                Bind();

                Total_qty1 = ((checkstockset_product_class)Session["checkstockset_product"]).Total_qty1.ToString();
                Total_qty2 = ((checkstockset_product_class)Session["checkstockset_product"]).Total_qty2.ToString();
            }
        }

        //添加产品
        protected void btAddproduct_Click(object sender, EventArgs e)
        {
            alert_msg = "";

            string areaid = uc_from_area.getValue();
            string storageid = uc_from_storageset.getValue();
            string productu_code = uc_from_product.getValue();
            string qty = txt_qty.Text.Trim();

            if (String.IsNullOrEmpty(areaid))
            {
                alert_msg = String.Format(Scripts.alert_warning, "请选择库区");
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
                return;
            }

            if (String.IsNullOrEmpty(storageid))
            {
                alert_msg = String.Format(Scripts.alert_warning, "请选择库位");
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
                return;
            }

            if (String.IsNullOrEmpty(productu_code))
            {
                alert_msg = String.Format(Scripts.alert_warning, "请输入货品条码");
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
                return;
            }

            if (String.IsNullOrEmpty(qty))
            {
                alert_msg = String.Format(Scripts.alert_warning, "请输入数量");
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
                return;
            }

            if (((checkstockset_product_class)Session["checkstockset_product"]).Add(areaid, storageid, productu_code, "0", qty, ref alert_msg) == false)
            {
                alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            uc_from_product.clearValue();
            txt_qty.Text = "";
            
            Bind();

            Total_qty1 = ((checkstockset_product_class)Session["checkstockset_product"]).Total_qty1.ToString();
            Total_qty2 = ((checkstockset_product_class)Session["checkstockset_product"]).Total_qty2.ToString();
        }

        //保存
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (GetParma() == false)
            {
                return;
            }

            alert_msg = "";

            if (((checkstockset_product_class)Session["checkstockset_product"]).getListTotal() <= 0)
            {
                alert_msg = String.Format(Scripts.alert_warning, "请输入盘点的货品信息");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            //保存数据入数据库
            using (edowork.com.SQL2005.TranUtil tranutil = new TranUtil(Session["connectionString"].ToString()))
            {
                System.Data.SqlClient.SqlTransaction tran = null;

                try
                {
                    tran = tranutil.GetSqlTransaction();
                }
                catch (Exception er)
                {
                    alert_msg = String.Format(Scripts.alert_warning, er.Message);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                edowork.com.SQL2005.Execute exec = new Execute(Session["connectionString"].ToString());

                string sql = "";
                int result = -1;

                //清空check_stock_detail中的数据
                sql = String.Format("delete from check_stock_detail where csid='{0}'", id);

                result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                if (result <= 0)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                DataTable dtData = ((checkstockset_product_class)Session["checkstockset_product"]).getList().Copy();

                foreach (DataRow dr in dtData.Rows)
                {
                    //保存入check_stock_detail表
                    sql = String.Format("insert into check_stock_detail(csid, storageid, productcode, Qty1, Qty2) values('{0}', '{1}', '{2}', {3}, {4})",
                                         id, dr["storageid"].ToString(), dr["productcode"].ToString(), dr["Qty1"].ToString(), dr["Qty2"].ToString());

                    result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                    if (result <= 0)
                    {
                        tran.Rollback();
                        tranutil.CloseConnection();

                        alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                        return;
                    }
                }

                tran.Commit();
                tranutil.CloseConnection();
            }

            alert_msg = String.Format(Scripts.alert_success, Errormsg.success_Save);

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
        }

        //返回
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            GetParma();

            string url = String.Format("/system/checkstock/checkstockset_list.aspx?start_date={0}&end_date={1}&csid={2}", start_date, end_date, csid);

            Response.Redirect(url);
        }

        //库位的选择
        protected void uc_from_area_OnbtSelect_Click(object sender, EventArgs e)
        {
            string areadid = uc_from_area.getValue();

            if (String.IsNullOrEmpty(areadid))
            {
                return;
            }

            uc_from_storageset.setStorage(areadid);
        }

        //删除与保存
        protected void rplist_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string id = e.CommandArgument.ToString();
            string qty2 = ((TextBox)e.Item.FindControl("txtQty2")).Text.Trim();

            switch (e.CommandName)
            {
                case "Delete":
                    {
                        ((checkstockset_product_class)Session["checkstockset_product"]).Delect(id);

                        //查询
                        Bind();

                        alert_msg = String.Format(Scripts.alert_success, Errormsg.success_Delete);

                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                        Total_qty1 = ((checkstockset_product_class)Session["checkstockset_product"]).Total_qty1.ToString();
                        Total_qty2 = ((checkstockset_product_class)Session["checkstockset_product"]).Total_qty2.ToString();

                        break;
                    }
                case "Save":
                    {
                        Save(id, qty2);

                        //查询
                        Bind();

                        Total_qty1 = ((checkstockset_product_class)Session["checkstockset_product"]).Total_qty1.ToString();
                        Total_qty2 = ((checkstockset_product_class)Session["checkstockset_product"]).Total_qty2.ToString();

                        break;
                    }
                default:
                    {
                        break;
                    }
            }
        }
    }
}